package ThreadDemo;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 34255
 * Date: 2024-10-15
 * Time: 11:19
 */
class Count1{
    private static int count = 0;

    public static int getCount() {
        return count;
    }

//    synchronized public static void setCount() {//方法用synchronized修饰等同与针对this进行加锁
//        count++;
//    }

    public static void setCount(){
        synchronized(Count1.class){
            count++;
        }
    }
}
public class Demo17 {
    public static void main(String[] args) throws InterruptedException {
        Thread thread1 = new Thread(() -> {
            synchronized (Object.class) {//锁对象
                for (int i = 0; i < 50000; i++) {
                    Count1.setCount();
                }
            }
        });

        Thread thread2 = new Thread(() -> {
            synchronized (Object.class) {//锁对象
                for (int i = 0; i < 50000; i++) {
                    Count1.setCount();
                }
            }
        });

        thread1.start();
        thread2.start();
        thread1.join();//让main线程等待thread1的线程任务执行完毕，才能接受操作系统线程调度
        thread2.join();//让main线程等待thread2的线程任务执行完毕，才能接受操作系统线程调度

        System.out.println("count = " + Count1.getCount());
        //打印出0，代表其他线程还没开始执行任务，main主线程就提前结束
    }
}
